//
//  main.m
//  链表
//
//  Created by apple on 15/7/29.
//  Copyright (c) 2015年 戴维营. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef struct student
{
    char name[20];
    int age;
    float weight;
    float height;
    
    struct student *next;
    
} student;

//创建链表

student *createlink(int n)
{
    student *p = NULL;
    student *pi = NULL;

    if (n)
    {
        p = malloc(sizeof(student));
        p->age = arc4random_uniform(100);
        p->next = NULL;
    
        pi = p;   // 将没用的指针悬空
        NSLog(@"$>age: %d",p->age);
    }
    for (int i = 0; i <= n - 1; i++)
    {
        p = malloc(sizeof(student));
        p->age = arc4random_uniform(100);
        p->next = NULL;
        
        //更新尾部的指针
        
        pi->next = p;
        pi = p;
        
        NSLog(@"@>age; %d",p->age);
    }
    return p;
}

//需要从前往后一个节点一个节点的释放

void release(student *link)
{
    student *p2 = link;
    while (p2)
    {
        link = p2->next;
        free(p2);
        
        p2 = link;
    }

}

void travel(student *link)
{
    if (link)
    {
        NSLog(@"#%d",link->age);
        travel(link->next);
    }
}

//主体函数部分

int main(int argc, const char * argv[]) {
    @autoreleasepool
    {
        student *link = createlink(10);
        
        NSLog(@"-------------");
        
        student *p2 = link;
        while (p2)
        {
            NSLog(@"age = %d",p2->age);
            p2 = p2->next;
        }
        
        NSLog(@"--------------");
        travel(link);
        
        release(link);
    }
    return 0;
}
